﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using Model;

namespace TanHungLong
{
    public partial class FrmPhieuYeuCau : DevExpress.XtraEditors.XtraForm
    {
        #region variant
        private FormStatus formStatus = FormStatus.View;
        private bool allowCloseForm = true;
        private MatHangBOCollection MatHangBOCollection = null;
        private NhomHangBOCollection nhomHangBOCollection = null;
        private PhieuYeuCauBOCollection PhieuYeuCauBOCollection = null;
        public static PhieuYeuCauChiTietBOCollection PhieuYeuCauChiTietBOCollection = PhieuYeuCauChiTietBOCollection.NewPhieuYeuCauChiTietBOCollection();
        public static PhieuYeuCauBO PhieuYeuCauBO = PhieuYeuCauBO.NewRootPhieuYeuCauBO();
        public static int daluu = 0;

        #endregion variant

        //=====================================
        #region form
        public FrmPhieuYeuCau()
        {
            InitializeComponent();
            this.KeyPreview = true;

            this.Load += new EventHandler(FrmPhieuYeuCau_Load);
            this.FormClosing += new FormClosingEventHandler(FrmPhieuYeuCau_FormClosing);
            this.KeyDown += new KeyEventHandler(this.FrmHoadonnhap_KeyDown);

            this.btnAdd.Click += new EventHandler(btnAdd_Click);
            this.btnXoa.Click += new EventHandler(btnDelete_Click);
            this.btnSave.Click += new EventHandler(btnSave_Click);
            this.btnCancel.Click += new EventHandler(btnCancel_Click);
            this.btnClose.Click += new EventHandler(btnClose_Click);
            this.btnRefresh.Click += new EventHandler(btnRefresh_Click);
            this.btnRefreshMatHang.Click += new EventHandler(btnRefreshMatHang_Click);
            this.toolStripMenuItemChuyenDoiHoaDon.Click += new System.EventHandler(this.toolStripMenuItemChuyenDoiHoaDon_Click);
            this.btnThanhToan.Click += new EventHandler(this.toolStripMenuItemChuyenDoiHoaDon_Click); ;

            this.grdViewMatHang.DoubleClick += new System.EventHandler(this.grdViewMatHang_DoubleClick);
            this.gridViewPhieuYeuCau.RowCellClick += new RowCellClickEventHandler(this.gridViewPhieuYeuCau_RowCellClick);

            this.grdViewMatHang.RowCellStyle += new RowCellStyleEventHandler(grdView_RowCellStyle);
            this.grdViewPhieuYeuCauChiTiet.RowCellStyle += new RowCellStyleEventHandler(grdView_RowCellStyle);

            this.grdViewMatHang.ShowingEditor += new CancelEventHandler(grdView_ShowingEditor);
            this.grdViewPhieuYeuCauChiTiet.ShowingEditor += new CancelEventHandler(grdView_ShowingEditor);


            this.lookUpMaKhachHang.EditValueChanged += new EventHandler(lookUpMaKhachHang_EditValueChanged);

            this.lookUpEditKhachHang.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(lookUpEditKhachHang_ButtonClick);
        }


        void lookUpMaKhachHang_EditValueChanged(object sender, EventArgs e)
        {
            lookUpEditKhachHang.EditValue = lookUpMaKhachHang.EditValue;
        }


        private void FrmPhieuYeuCau_Load(object sender, EventArgs e)
        {
            //SetFormStatus(this.formStatus);

            Utility.InitControl(this.reItemLookUpEditDonViTinh);
            Utility.InitControl(this.reItemLookUpEditMatHang);
            Utility.InitControl(this.reItemLookUpEditKhachHangID);

            Utility.InitControl(this.lookUpNhanVienID);

            RefreshData();

            this.grdViewMatHang.FocusedRowChanged += new FocusedRowChangedEventHandler(grdViewMatHang_FocusedRowChanged);
            this.grdView.FocusedRowChanged += new FocusedRowChangedEventHandler(grdView_FocusedRowChanged);
            this.txtTimkiem.EditValueChanged += new System.EventHandler(this.txtTimkiem_EditValueChanged);
            this.grdViewPhieuYeuCauChiTiet.CellValueChanged += new CellValueChangedEventHandler(this.grdViewPhieuYeuCauChiTiet_CellValueChanged);
        }

        private void FrmPhieuYeuCau_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.allowCloseForm == false)
                e.Cancel = true;
        }

        private void FrmHoadonnhap_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyData == Keys.Delete)
            {
                DeleteMatHang();
            }

            if (e.KeyCode == Keys.N && Control.ModifierKeys == Keys.Control)
                AddNew();
            if ((e.KeyCode == Keys.Q && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F10))
                this.Close();
            if ((e.KeyCode == Keys.R && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F5))
                RefreshData();
            if ((e.KeyCode == Keys.S && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F6))
                Save();
            if ((e.KeyCode == Keys.T && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F2))
                toolStripMenuItemChuyenDoiHoaDon_Click(null, null);
            if ((e.KeyCode == Keys.Delete && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F8))
                btnDelete_Click(null, null);
        }
        #endregion form

        //=====================================
        #region control


        void lookUpEditKhachHang_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {
                FrmNewKhachHang.daluu = 0;
                FrmNewKhachHang frNewKH = new FrmNewKhachHang();
                frNewKH.ShowDialog();
                if (FrmNewKhachHang.daluu == 1)
                {
                    KhachHangBOCollection nn = KhachHangBOCollection.GetKhachHangBOCollection("KH = 1");
                    bdSourceKhachHang.DataSource = nn.Clone();
                    lookUpEditKhachHang.EditValue = lookUpMaKhachHang.EditValue = StaticUtil.GetInt(FrmNewKhachHang.KhachHangBO.KhachHangID, -1);
                    FrmNewKhachHang.daluu = 0;
                }
            }
            else
                if (e.Button.Index == 2)
                    lookUpEditKhachHang.EditValue = null;
        }
        #endregion control

        //=====================================
        #region button
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void btnRefreshMatHang_Click(object sender, EventArgs e)
        {
            FilterMatHangByName("");
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddNew();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            Edit();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Cancel();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int _phieuYeuCauID = StaticUtil.GetInt(PhieuYeuCauBO.PhieuYeuCauID, -1);
            if (_phieuYeuCauID != -1)
            {
                if (MessageBox.Show("Bạn muốn xóa Phiếu yêu cầu này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Model.PhieuYeuCauBO.DeletePhieuYeuCauBO(_phieuYeuCauID);
                    for (int k = 0; k < PhieuYeuCauChiTietBOCollection.Count; k++)
                    {
                        PhieuYeuCauChiTietBO.DeletePhieuYeuCauChiTietBO((int)PhieuYeuCauChiTietBOCollection[k].PhieuYeuCauChiTietID);
                    }
                    RefreshData();
                    btnAdd_Click(e, e);
                }
            }
            else
            {
                MessageBox.Show("Chưa chọn Phiếu yêu cầu để xóa! ", "Thông báo", MessageBoxButtons.OK);
            }
        }
        #endregion button

        //=====================================
        #region grid
        private void grdViewMatHang_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            //FilterMatHang();
        }

        private void grdView_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            FilterMatHang();
        }


        private void grdView_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView grdView = (GridView)sender;

            bool del = StaticUtil.GetBool(grdView.GetFocusedRowCellValue("DELE"));
            string fieldName = grdView.FocusedColumn.FieldName;

            if (del && fieldName != "DELE")
                e.Cancel = true;
            else
                if (fieldName == "DELE" && grdView.FocusedRowHandle == GridControl.NewItemRowHandle)
                    e.Cancel = true;
        }

        private void grdView_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            bool del = StaticUtil.GetBool(this.grdViewMatHang.GetRowCellValue(e.RowHandle, "DELE"));

            if (del)
            {
                e.Appearance.Font = MyStyle.DELETE_FONT;
                e.Appearance.ForeColor = MyStyle.DELETE_COLOR;
            }
        }

        private void grdViewMatHang_DoubleClick(object sender, EventArgs e)
        {
            UpdatePhieuYeuCau();
        }


        private void grdViewPhieuYeuCauChiTiet_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                int _stt = StaticUtil.GetInt(this.grdViewPhieuYeuCauChiTiet.GetFocusedRowCellValue("STT0"));
                //int _idDonViTinh = StaticUtil.GetInt(this.grdViewPhieuYeuCauChiTiet.GetFocusedRowCellValue("DonViTinhID"));
                double _dai = StaticUtil.GetDouble(this.grdViewPhieuYeuCauChiTiet.GetFocusedRowCellValue("Dai"), 0);
                double _rong = StaticUtil.GetDouble(this.grdViewPhieuYeuCauChiTiet.GetFocusedRowCellValue("Rong"), 0);
                double _soluongM = StaticUtil.GetDouble(this.grdViewPhieuYeuCauChiTiet.GetFocusedRowCellValue("SoLuongM"), 0);

                //int kiemtraID = PhieuYeuCauChiTietBOCollection.CheckExits(_idMatHang, _idDonViTinh);
                double _tongcongM = _dai * _rong * _soluongM;

                PhieuYeuCauChiTietBOCollection[_stt - 1].TongCongM = _tongcongM;
                //PhieuYeuCauChiTietBOCollection[kiemtraID].SoLuong = _tongcongM;
                sapxep();
            }
            catch { }
        }


        private void gridViewPhieuYeuCau_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            int phieuYeuCauID = StaticUtil.GetInt(gridViewPhieuYeuCau.GetFocusedRowCellValue("PhieuYeuCauID"));
            //int kiemtraID = kiemtra(HoadonnhapChitietBOCollection, (int)_id);
            //if (kiemtraID == -1)
            //{
            PhieuYeuCauBO = Model.PhieuYeuCauBO.GetRootPhieuYeuCauBO(phieuYeuCauID);
            PhieuYeuCauChiTietBOCollection = Model.PhieuYeuCauChiTietBOCollection.GetPhieuYeuCauChiTietBOCollection("PhieuYeuCauID = " + phieuYeuCauID.ToString());

            lookUpEditKhachHang.EditValue = PhieuYeuCauBO.KhachHangID.Value;
            lookUpNhanVienID.EditValue = PhieuYeuCauBO.NguoiThucHienID.Value;
            txtMaSo.Text = PhieuYeuCauBO.MaSo;
            txtNoidung.Text = PhieuYeuCauBO.NoiDung;
            txtNguoiYeuCau.Text = PhieuYeuCauBO.NguoiYeuCau;
            dtNgayLapPhieu.DateTime = PhieuYeuCauBO.NgayLapPhieu.Value;

            //bdSourcePhieuYeuCauChiTiet.DataSource = PhieuYeuCauChiTietBOCollection.Clone();


            sapxep();
        }


        #endregion grid


        //=====================================
        #region Texbox

        private void txtTimkiem_EditValueChanged(object sender, EventArgs e)
        {
            FilterMatHangByName(txtTimkiem.Text.Trim());
        }

        #endregion Texbox

        //=====================================
        #region function
        private void FilterMatHang()
        {
            Session.NhomHangID = StaticUtil.GetRealInt(this.grdView.GetFocusedRowCellValue("NhomHangID"));

            if (Session.NhomHangID == -1)
            {
                //this.grdViewPhieuYeuCauChiTiet.ActiveFilterString = "MatHangID=" + int.MaxValue;

                this.MatHangBOCollection = MatHangBOCollection.GetMatHangBOCollection();
                this.bdSourceMatHang.DataSource = this.MatHangBOCollection.Clone();
            }
            else
            {
                //this.grdViewPhieuYeuCauChiTiet.ActiveFilterString = "MatHangID=" + int.MaxValue;

                this.MatHangBOCollection = MatHangBOCollection.GetMatHangBOCollection("NhomHangID = " + Session.NhomHangID.ToString());
                this.bdSourceMatHang.DataSource = this.MatHangBOCollection.Clone();
            }
            //this.grdViewPhieuYeuCauChiTiet.CheckLoaded();
            //SetSttPhieuYeuCauChiTiet();
        }

        private void FilterMatHangByName(string nameMatHang)
        {
            this.MatHangBOCollection = MatHangBOCollection.GetMatHangBOCollection("Ten like N'%" + nameMatHang + "%'");
            this.bdSourceMatHang.DataSource = this.MatHangBOCollection.Clone();
        }

        private void ResetData()
        {
            NhanVienBOList nhanVienBOList = NhanVienBOList.GetNhanVienBOList();
            Utility.SetData(this.lookUpNhanVienID, nhanVienBOList, nhanVienBOList.Count);

            txtMaSo.Text = "PYC-" + DateTime.Now.ToString("dd/MM/yyyy") + "-";
            txtNoidung.Text = "";
            dtNgayLapPhieu.DateTime = DateTime.Now;
            PhieuYeuCauBO = Model.PhieuYeuCauBO.NewRootPhieuYeuCauBO();
            PhieuYeuCauChiTietBOCollection = Model.PhieuYeuCauChiTietBOCollection.NewPhieuYeuCauChiTietBOCollection();
            bdSourcePhieuYeuCauChiTiet.DataSource = PhieuYeuCauChiTietBOCollection.Clone();
        }

        private void RefreshData()
        {
            #region

            DanhMucBOList donViTinhBOList = DanhMucBOList.GetDanhMucBOList(LoaiDanhMuc.DonViTinh);
            Utility.SetData(this.reItemLookUpEditDonViTinh, donViTinhBOList, donViTinhBOList.Count);

            MatHangBOList matHangBOList = MatHangBOList.GetMatHangBOList();
            Utility.SetData(this.reItemLookUpEditMatHang, matHangBOList, matHangBOList.Count);

            KhachHangBOList khachHangBOList = KhachHangBOList.GetKhachHangBOList();
            Utility.SetData(this.reItemLookUpEditKhachHangID, khachHangBOList, khachHangBOList.Count);
            //this.bdSourceKhachHang.DataSource = khachHangBOList.Clone();
            //this.lookUpKhachHangID.Properties.DataSource = khachHangBOList;

            KhachHangBOCollection khachHangBOColl = KhachHangBOCollection.GetKhachHangBOCollection("KH = 1");
            bdSourceKhachHang.DataSource = khachHangBOColl.Clone();
            #endregion BOList

            this.MatHangBOCollection = MatHangBOCollection.GetMatHangBOCollection();
            //this.PhieuYeuCauChiTietBOCollection = PhieuYeuCauChiTietBOCollection.GetPhieuYeuCauChiTietBOCollection();
            this.PhieuYeuCauBOCollection = Model.PhieuYeuCauBOCollection.GetPhieuYeuCauBOCollection("ThucHien = 0");
            this.nhomHangBOCollection = NhomHangBOCollection.GetNhomHangBOCollection();

            NhomHangBO NewNhomHangBO = NhomHangBO.NewRootNhomHangBO();
            NewNhomHangBO.Ten = "Tất cả";
            NewNhomHangBO.NhomHangID = -1;
            this.nhomHangBOCollection.Add(NewNhomHangBO);

            this.bdSourceMatHang.DataSource = this.MatHangBOCollection.Clone();
            //this.bdSourcePhieuYeuCauChiTiet.DataSource = this.PhieuYeuCauChiTietBOCollection.Clone();
            this.bdSourceNhomHang.DataSource = this.nhomHangBOCollection.Clone();
            this.bdSourcePhieuYeuCau.DataSource = this.PhieuYeuCauBOCollection.Clone();

            ResetData();

            FilterMatHang();
        }

        private void Edit()
        {
            this.formStatus = FormStatus.Edit;
            //SetFormStatus(this.formStatus);
            Session.CloseIndex++;
        }

        private void AddNew()
        {
            PhieuYeuCauBO = Model.PhieuYeuCauBO.NewRootPhieuYeuCauBO();
            PhieuYeuCauChiTietBOCollection = Model.PhieuYeuCauChiTietBOCollection.NewPhieuYeuCauChiTietBOCollection();
            ResetData();
        }

        private void Save()
        {
            if (kiemtraLuu() == 1)
            {
                PhieuYeuCauBO.KhachHangID = Convert.ToInt32(lookUpEditKhachHang.EditValue);
                PhieuYeuCauBO.MaSo = txtMaSo.Text.Trim();
                PhieuYeuCauBO.NgayLapPhieu = dtNgayLapPhieu.DateTime;
                PhieuYeuCauBO.NoiDung = txtNoidung.Text.Trim();
                PhieuYeuCauBO.NguoiYeuCau = txtNguoiYeuCau.Text.Trim();
                PhieuYeuCauBO.NguoiThucHienID = Convert.ToInt32(lookUpNhanVienID.EditValue);
                PhieuYeuCauBO.ThucHien = 0;
                PhieuYeuCauBO.Save();

                int recordCount = PhieuYeuCauChiTietBOCollection.Count;
                if (recordCount > 0)
                {
                    for (int i = 0; i < recordCount; i++)
                    {
                        PhieuYeuCauChiTietBOCollection[i].PhieuYeuCauID = PhieuYeuCauBO.PhieuYeuCauID.Value;
                    }

                    PhieuYeuCauChiTietBOCollection.Save();
                }

                MessageBox.Show("Cập nhật thành công! ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);

                PhieuYeuCauChiTietBOCollection = PhieuYeuCauChiTietBOCollection.Save();
                PhieuYeuCauBOCollection = Model.PhieuYeuCauBOCollection.GetPhieuYeuCauBOCollection("ThucHien = 0");
                this.bdSourcePhieuYeuCau.DataSource = this.PhieuYeuCauBOCollection.Clone();
                this.bdSourcePhieuYeuCauChiTiet.DataSource = PhieuYeuCauChiTietBOCollection.Clone();
            }


            FilterMatHang();
        }

        private void Cancel()
        {
            this.formStatus = FormStatus.View;
            //SetFormStatus(this.formStatus);
            Session.CloseIndex--;

            this.bdSourceMatHang.DataSource = this.MatHangBOCollection.Clone();
            this.bdSourcePhieuYeuCauChiTiet.DataSource = PhieuYeuCauChiTietBOCollection.Clone();

            FilterMatHang();
        }

        private void UpdatePhieuYeuCau()
        {
            int MatHangID = StaticUtil.GetInt(grdViewMatHang.GetFocusedRowCellValue("MatHangID"));
            //int kiemtraID = kiemtra(HoadonnhapChitietBOCollection, (int)_id);
            //if (kiemtraID == -1)
            //{
            PhieuYeuCauChiTietBO newBO = PhieuYeuCauChiTietBO.NewRootPhieuYeuCauChiTietBO();
            newBO.MatHangID = MatHangID;
            PhieuYeuCauChiTietBOCollection.Add(newBO);

            sapxep();

        }

        private void sapxep()
        {

            int length = PhieuYeuCauChiTietBOCollection.Count;

            for (int i = 0; i < length; i++)
            {
                PhieuYeuCauChiTietBOCollection[i].STT0 = (i + 1);
            }

            bdSourcePhieuYeuCauChiTiet.DataSource = PhieuYeuCauChiTietBOCollection;
        }

        private void DeleteMatHang()
        {

            if (MessageBox.Show("Bạn có muốn xóa Mặt Hàng và Đơn vị tính này không? ", "Cảnh báo!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                int _phieuYeuCauChiTietID = StaticUtil.GetInt(this.grdViewPhieuYeuCauChiTiet.GetFocusedRowCellValue("PhieuYeuCauChiTietID"), -1);
                int _stt = StaticUtil.GetInt(this.grdViewPhieuYeuCauChiTiet.GetFocusedRowCellValue("STT0"), -1);

                if (_phieuYeuCauChiTietID >=0)
                {
                    PhieuYeuCauChiTietBO.DeletePhieuYeuCauChiTietBO(_phieuYeuCauChiTietID);
                    PhieuYeuCauChiTietBOCollection.Remove(_phieuYeuCauChiTietID);
                }
                else
                    if (_stt >= 0)
                    {
                        PhieuYeuCauChiTietBOCollection.RemoveSTT(_stt);
                    }
                sapxep();
            }
        }

        private int kiemtraLuu()
        {
            int tempkiemtra = 1;
            string strError = "";

            if (lookUpEditKhachHang.EditValue == null)
            {
                tempkiemtra = 0;
                strError = "Chưa chọn Khách hàng";
            }

            //if (lookUpNhanVienID.EditValue == null)
            //{
            //    tempkiemtra = 0;
            //    strError = strError + " ;Chưa chọn Người thực hiện";
            //}

            if (txtMaSo.Text.Trim() == "")
            {
                tempkiemtra = 0;
                strError = strError + " ;Chưa nhập Mã số";
            }

            //if (txtNoidung.Text.Trim() == "")
            //{
            //    tempkiemtra = 0;
            //    strError = strError + " ;Chưa nhập Nội dung";
            //}
            if (tempkiemtra == 0)
                MessageBox.Show(strError, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return tempkiemtra;
        }

        #endregion function

        private void toolStripMenuItemChuyenDoiHoaDon_Click(object sender, EventArgs e)
        {
            daluu = 0;
            if (StaticUtil.GetRealInt(PhieuYeuCauBO.PhieuYeuCauID.Value, -1) >= 0)
            {
                FrmHoaDonBanChiTiet.hientrang = 1;
                FrmHoaDonBanChiTiet frm = new FrmHoaDonBanChiTiet();
                frm.ShowDialog();
            }
            else
            {
                MessageBox.Show("Chưa chọn Phiếu Yêu Cầu để Chuyển đổi! ", "Thông báo", MessageBoxButtons.OK);
            }

            if (daluu == 1)
            {
                RefreshData();
                daluu = 0;
            }
            FrmHoaDonBanChiTiet.hientrang = 0;
        }


        private void toolStripMenuItemChuyenDoiNguyenTrang_Click(object sender, EventArgs e)
        {
            daluu = 0;
            if (StaticUtil.GetRealInt(PhieuYeuCauBO.PhieuYeuCauID.Value, -1) >= 0)
            {
                FrmHoaDonBanChiTiet.hientrang = 0;
                FrmHoaDonBanChiTiet frm = new FrmHoaDonBanChiTiet();
                frm.ShowDialog();
            }
            else
            {
                MessageBox.Show("Chưa chọn Phiếu Yêu Cầu để Chuyển đổi! ", "Thông báo", MessageBoxButtons.OK);
            }

            if (daluu == 1)
            {
                RefreshData();
                daluu = 0;
            }

        }
    }
}